import cv2
import pyautogui
from pyscreeze import ImageNotFoundException

#读大图。画框需要图像数据
img = cv2.imread('../ScnPhoto/T5.png')#大图
myConfidence = 0.9  # 我的牌的置信度max=1
otherConfidence = 0.95  # 别人的牌的置信度
whiteConfidence = 0.97  # 检测白块的置信度
myFilter = 19  # 两牌之间的距离。小于此值视为同一张牌。我的牌。
otherFilter = 15  # 单位像素。别人的牌检测结果过滤参数
all_results = []
Who_CardsNum = {'rdw': 0,
              'bxw': 0,
              'b2': 0,
              'r2': 0,
              'bA': 0,
              'rA': 0,
              'bK': 0,
              'rK': 0,
              'bQ': 0,
              'rQ': 0,
              'bJ': 0,
              'rJ': 0,
              'b10': 0,
              'r10': 0,
              'b9': 0,
              'r9': 0,
              'b8': 0,
              'r8': 0,
              'b7': 0,
              'r7': 0,
              'b6': 0,
              'r6': 0,
              'b5': 0,
              'r5': 0,
              'b4': 0,
              'r4': 0,
              'b3': 0,
              'r3': 0,
              }

def cv_show(title,img):
    cv2.imshow(title,img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    return

# 去除重复的匹配结果，返回数值
def cardsFilter(location, distance):  # 牌检测结果滤波
    if len(location) == 0:
        return 0
    locList = [location[0][0]]  # 第一个元组的Left值。
    # [(left, top, width, height), (left...
    count = 1
    for e in location:#对每一个元组
        flag = 1  # “是新的”标志
        for have in locList:
            if abs(e[0]-have) <= distance: #很近
                flag = 0 #重复
                break#结束for have循环，后面没必要比较了
        if flag:
            count += 1
            locList.append(e[0])
    return count

#找小图
# -----
# try:
#     result = pyautogui.locateAll(needleImage='./pics/white.png',
#                                  confidence=whiteConfidence,
#                                  haystackImage=img,grayscale=False)#默认grayscale=True灰度模式
#     all_results.extend(list(result))# 存结果
#     print(cardsFilter(all_results, myFilter))  # 去重后结果的个数
# except ImageNotFoundException:
#     print('0个')
# -----
# locateAll内部调用OpenCV的cv2.matchTemplate。
#needleImage(小图)要找的目标。从haystackImage(大图)找。
# result是生成器对象，生成的是(left, top, width, height)
# print(result)# <generator object ...>
# print(list(result)) 迭代器只能被用一次
#[Box(left=np.int64(51), top=np.int64(15), width=75, height=97), Box(left...

# 遍历-我-手牌小图
for i in Who_CardsNum.keys():
    try:
        result = pyautogui.locateAll(needleImage='pics/m' + i + '.png',
                                     haystackImage=img,grayscale=False,
                                     confidence=myConfidence)#默认grayscale=True灰度模式
        l_result=list(result)#生成器对象转换为列表
        Who_CardsNum[i] = cardsFilter(l_result, myFilter)  # 去重后结果的个数
        all_results.extend(l_result)# 存结果
    except ImageNotFoundException:
        continue  # 继续处理下一张卡牌

# 遍历-别人-手牌小图
# for i in Who_CardsNum.keys():
#     try:
#         result = pyautogui.locateAll(needleImage='pics/o' + i + '.png',
#                                      haystackImage=img,grayscale=False,
#                                      confidence=otherConfidence)#默认grayscale=True灰度模式
#         l_result=list(result)#生成器对象转换为列表
#         Who_CardsNum[i] = cardsFilter(l_result, otherFilter)  # 去重后结果的个数
#         all_results.extend(l_result)# 存结果
#     except ImageNotFoundException:
#         continue  # 继续处理下一张卡牌
# print(Who_CardsNum)

# 画框
# 遍历匹配结果并绘制矩形
for match in all_results:
    left, top, width, height = match
    bottom_right = (left + width, top + height)
    cv2.rectangle(img, (left, top), bottom_right, (0, 255, 0), 2)
cv_show('resoult',img)